﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Windows.Forms;

namespace Out2Share
{
    /// <summary>
    /// Thread to search children nodes of a Sharepoint WebSite
    /// </summary>
    public class NodeFinderThread
    {
        ConfData conf;
        string url;
        string library;
        TreeViewContainer treeview;
        public NodeFinderThread(TreeViewContainer _treeview, ConfData _conf, string _url)
        {
            treeview = _treeview;
            conf = _conf;
            url = _url;
        }
        public NodeFinderThread(TreeViewContainer _treeview, ConfData _conf, string _url, string _library)
        {
            treeview = _treeview;
            conf = _conf;
            url = _url;
            library = _library;
        }
        public void Find()
        {
            try
            {
                // Sites
                SharepointWebs.WebsSoapClient clientWeb = SharepointHelper.GetWebsSoapClient(conf, url);
                XElement xElementWeb = clientWeb.GetWebCollection();

                // Lists
                SharepointLists.ListsSoapClient clientList = SharepointHelper.GetListsSoapClient(conf,url);
                XElement xElementList = clientList.GetListCollection();

                treeview.Invoke(treeview.addListItemDelegate,
                                       new Object[] { xElementWeb, xElementList });
            }
            catch (Exception e) {
                treeview.Invoke(treeview.ErrorOnThreadDelegate,
                                      new Object[] { e.Message });
            }
        }
        public void FindFolder()
        {
            try
            {
                // Sites
                SharepointSiteData._sFPUrl[] enArray;

                SharepointSiteData.SiteDataSoapClient clientWeb = SharepointHelper.GetSiteDataClient(conf,url);
                clientWeb.EnumerateFolder(library,out enArray);
                List<string> urls = new List<string>();
                foreach (SharepointSiteData._sFPUrl en in enArray)
                {
                    if (en.IsFolder && !en.Url.EndsWith("Forms"))
                    {
                        urls.Add(en.Url);
                    }
                }

                treeview.Invoke(treeview.AddFolderDelegate,
                                       new Object[] {urls });
            }
            catch (Exception e)
            {
                //treeview.Invoke(treeview.ErrorOnThreadDelegate, new Object[] { e.Message });
                List<string> urls = new List<string>();
                treeview.Invoke(treeview.AddFolderDelegate,
                                       new Object[] {urls });
            
            }
        }
    }
}
